import { setLocalUser,removeLocalUser,getLocalUser } from '@/utils/cookie'
import { login, loginCheckCode } from '@/api/login'

const getDefaultState = () => {
  return {
    user:{
      roleName:'',
      nickname:'',
      token:''
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  CHANGE_STATE: (state, {key,value}) => {
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  },
  // 读取并加载本地user信息
  READ_SETTING_LOCAL_USER:(state)=>{
    var user=getLocalUser();
    //console.log("读取并加载本地user信息 >>>",user)
    if(user) state['user'] = user;
  }
}

const actions = {
  // user login
  async login({ commit }, data) {
    const res=await login(data);
    const user=res.data;
    //清理旧的user数据
    commit('RESET_STATE')
    removeLocalUser();
    //保存新的user数据
    commit('CHANGE_STATE',{key:'user',value:user})
    setLocalUser(user);
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('RESET_STATE')
      removeLocalUser();
      commit('menu/RESET_STATE',{}, { root: true })
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
